package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.domain.User;
import com.qf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.jws.soap.SOAPBinding;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

/**
 * @author YDW
 * projectName:shopping
 * time:2022/4/18 17:37
 * description:用户数据访问层接口实现类
 */
public class UserDaoImpl implements UserDao {
    QueryRunner queryRunner=new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public Long selectByUsername(String username) {
        String sql=" select count(0) from tb_user where username=? ";
        try {
            Long count=(Long)queryRunner.query(sql,new ScalarHandler(),username);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Long.valueOf(0);
    }

    @Override
    public int insert(User user) {
        String sql=" insert into tb_user value (null,?,md5(?),?,?,?,?,?) ";
        try {
            Object[] params={user.getUsername(),user.getPassword(),user.getEmail(),user.getGender(),user.getFlag(),user.getRole(),user.getCode()};
            int count = queryRunner.update(sql, params);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public User selectByUsernameAndPassword(String username, String password) {
        String sql=" select id,username,password,email,gender,flag,role,code from tb_user where username=? and password=md5(?) and role=1 and flag=1 ";
        try {
            User user = queryRunner.query(sql, new BeanHandler<>(User.class), username, password);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User finduser(int uid) {
        String sql=" select id,username,password,email,gender,flag,role,code from tb_user where id=? ";
        try {
            User user = queryRunner.query(sql, new BeanHandler<>(User.class), uid);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<User> findUserByUsername(String username) {
        String sql=" select id,username,password,email,gender,flag,role,code from tb_user where username like '%"+username+"%' ";
        try {
            List<User> users = queryRunner.query(sql, new BeanListHandler<>(User.class));
            return users;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
